package com.liuzhilong.infrastructure.scene.idgenerate;

/**
 * 优化过后的 主要是解决时钟回拨问题。
 * 主要思想是通过更换workid进行生成。
 */
public class OptimizeSnowFlakes {

    /** 开始时间截 (2015-01-01) */
    private final long twepoch = 1420041600000L;

    /** 机器id所占的位数 */
    private final long workerIdBits = 5L;

    /** 数据标识id所占的位数 */
    private final long datacenterIdBits = 5L;

    /** 支持的最大机器id，结果是31 ) */
    private final long maxWorkerId = -1L ^ (-1L << workerIdBits);

    /** 支持的最大数据标识id，结果是31 */
    private final long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);

    /** 序列在id中占的位数 */
    private final long sequenceBits = 12L;

    /** 机器ID向左移12位 */
    private final long workerIdShift = sequenceBits;

    /** 数据标识id向左移17位(12+5) */
    private final long datacenterIdShift = sequenceBits + workerIdBits;

    /** 时间截向左移22位(5+5+12) */
    private final long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;

    /**
     * 生成序列的掩码，这里为4095 (0b111111111111=0xfff=4095)
     */
    private final long sequenceMask = -1L ^ (-1L << sequenceBits);

    /** 工作机器ID(0~31) */
    private long workerId;
    // 开始机器id
    private long startWorkerId;
    private long workerIdSpace;

    /** 数据中心ID(0~31) */
    private long datacenterId;

    /** 毫秒内序列(0~4095) */
    private long sequence = 0L;

    /** 上次生成ID的时间截 */
    private long lastTimestamp = -1L;

    /**
     * 构造函数
     * @param startWorkerId 开始 工作ID (0~31)
     * @param workerIdSpace 工作id间隔
     * @param datacenterId 数据中心ID (0~31)
     */
    public OptimizeSnowFlakes(long startWorkerId,int workerIdSpace, long datacenterId) {
        if (startWorkerId > maxWorkerId || startWorkerId < 0) {
            throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId));
        }
        long setworkidmax = startWorkerId + workerIdSpace - 1;
        if (setworkidmax > maxWorkerId || setworkidmax < 0) {
            throw new IllegalArgumentException(String.format("worker Id with its space plus  can't be greater than %d or less than 0", maxWorkerId));
        }
        if (datacenterId > maxDatacenterId || datacenterId < 0) {
            throw new IllegalArgumentException(String.format("datacenter Id can't be greater than %d or less than 0", maxDatacenterId));
        }
        this.workerId = startWorkerId;
        this.datacenterId = datacenterId;
    }

    // ==============================Methods==========================================
    /**
     * 获得下一个ID (该方法是线程安全的)
     * @return SnowflakeId
     */
    public synchronized long nextId() {
        long currentTimestamp = timestamp();

        //如果当前时间小于上一次ID生成的时间戳，说明系统时钟回退过这个时候应当抛出异常
        if (currentTimestamp < lastTimestamp) {
            // 设置不同的同步策略

            // 小于50ms的 阻塞到时间正常
            if(lastTimestamp-currentTimestamp<=50){
                currentTimestamp = waitToNextTimestamp(lastTimestamp);
            }else {
                // 直接切换workid
                this.workerId = nextWorkId(workerId);
                // 重新计数
                sequence = 0L;
            }


        }

        //如果是同一时间生成的，则进行毫秒内序列
        if (lastTimestamp == currentTimestamp) {
            sequence = (sequence + 1) & sequenceMask;
            //毫秒内序列溢出
            if (sequence == 0) {
                //阻塞到下一个毫秒,获得新的时间戳
                currentTimestamp = waitToNextTimestamp(lastTimestamp);
            }
        }
        //时间戳改变，毫秒内序列重置
        else {
            sequence = 0L;
        }

        //上次生成ID的时间截
        lastTimestamp = currentTimestamp;

        //移位并通过或运算拼到一起组成64位的ID
        return ((currentTimestamp - twepoch) << timestampLeftShift) //
                | (datacenterId << datacenterIdShift) //
                | (workerId << workerIdShift) //
                | sequence;
    }

    /**
     * dead loop，到下个毫秒数。
     * @param lastTimestamp 上次生成ID的时间截
     * @return 当前时间戳
     */
    protected long waitToNextTimestamp(long lastTimestamp) {
        long timestamp = timestamp();
        while (timestamp <= lastTimestamp) {
            timestamp = timestamp();
        }
        return timestamp;
    }

    /**
     *
     * @return 当前时间(毫秒)
     */
    protected long timestamp() {
        return System.currentTimeMillis();
    }

    /**
     * 根据{@code currentWorkId}和{@link #workerIdSpace} 进行偏移
     * @param currentWorkId
     * @return
     */
    private long nextWorkId(long currentWorkId) {
        return 0L;
    }


}
